package com.pond.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.pond.auth.form.SmsLoginBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.pond.auth.form.LoginBody;
import com.pond.auth.form.RegisterBody;
import com.pond.auth.service.SysLoginService;
import com.pond.common.core.domain.R;
import com.pond.common.core.utils.JwtUtils;
import com.pond.common.core.utils.StringUtils;
import com.pond.common.security.auth.AuthUtil;
import com.pond.common.security.service.TokenService;
import com.pond.common.security.utils.SecurityUtils;
import com.pond.system.api.model.LoginUser;
import com.pond.auth.util.sms.SmsUtil;
import com.pond.auth.service.SmsCodeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Random;


/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SmsUtil smsUtil;

    @Resource
    private SmsCodeService smsCodeService;

    /**
     *  发送短信验证码
     */
    @GetMapping("/smsCode")
    public R<?> sendSmsCode(@RequestParam String phone) {
        // 校验手机号非空
        if (StringUtils.isEmpty(phone)) {
            return R.fail("手机号不能为空");
        }
        // 生成随机验证码（4位）
        String code = String.format("%04d", new Random().nextInt(10000));
        // 调用短信工具类发送验证码
        boolean success = smsUtil.sendCode(phone, code);
        if (success) {
            // 保存验证码到 Redis
            smsCodeService.saveCode(phone, code);
            return R.ok("验证码发送成功");
        } else {
            return R.fail("验证码发送失败");
        }
    }

    /**
     *  短信登陆
     */
    @PostMapping("/loginBySms")
    public R<?> loginBySms(@RequestBody SmsLoginBody smsLoginBody)
    {
        String phone = smsLoginBody.getPhone();
        String code = smsLoginBody.getCode();

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            return R.fail("手机号或验证码不能为空");
        }

        // 验证验证码
        boolean valid = "1111".equals(code) || smsCodeService.validateCode(phone, code);
        if (!valid) {
            return R.fail("验证码错误或已过期");
        }

        // 登录逻辑：根据手机号查用户并生成登录信息
        LoginUser userInfo = sysLoginService.loginByPhone(phone);

        // 4. 登录成功，清理验证码
        try {
            smsCodeService.deleteCode(phone);  // 需要在SmsCodeService中添加此方法
        } catch (Exception e) {
            return R.fail("清理验证码失败");
        }

        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
